<template>
	<view>
		<view class="container">
			<view v-if="!open_leidr">
				<view style="position:fixed;top:0px;left:0px;bottom:0px;right:0px">
					<image src="../../static/images/homeBg.png" mode="aspectFit" style="width:100%;height:100%;padding-top:16%;"></image>
				</view>
				<view style="position:fixed;top:0px;left:5px;bottom:170px;right:5px;overflow:auto">
					<view>
						<view style="padding-left:10px;padding-top:10px;padding-bottom:10px;" class="flex">
							<image src="../../static/images/open_doot_tip.png" style="width:20px;height:20px"></image>
							<view class="flex_one" style="padding-left:5px"> 您有以下开门权限,点击下方开门按钮即可开门</view>
						</view>
						<view class="home" v-for="(item, index) in village_door" :key="index">
							<view class="weui-media-box weui-media-box_appmsg">
								<view class="weui-media-box__hd">
									<image src="../../static/images/openHome.png" class="weui-media-box__thumb border_radius" style="width:20px;height:21px"></image>
								</view>
								<view class="weui-media-box__bd w_3 flex">
									<view class="weui-media-box__title color_9 font_b font_size15 flex_one">
										<view class="flex_one h4">{{item.village_name}}</view>
										<block v-if="!item.have_village_door">
											<view class="flex_one time">小区暂未添加门禁</view>
										</block>
										<block v-else>
											<view class="flex_one time" v-if="item.have_floor_door">共有{{item.door_num}}个门禁</view>
											<view class="flex_one time" v-else>{{item.tip_info}}</view>
										</block>

									</view>
									<block v-if="(item.have_village_door && item.have_floor_door)">
										<view class="weui-media-box__desc all" @tap="is_all" :data-index="index" v-if="is_one!=1">{{item.is_all?'查看全部':'收起'}}</view>
									</block>

								</view>
							</view>
							<view class="home_detail" v-if="(item.door_list && !item.is_all) || is_one==1">
								<block v-for="(itemName, itemIndex) in item.door_list" :key="itemIndex">
									<view class="weui-media-box weui-media-box_appmsg border-t">
										<view class="weui-media-box__hd">
											<image src="../../static/images/openKey.png" class="weui-media-box__thumb border_radius" style="width:20px;height:20px"></image>
										</view>
										<view class="weui-media-box__bd w_3 flex">
											<view class="weui-media-box__title color_9 font_b font_size15 flex_one">
												<view class="flex_one h4 flex" style="font-weight:normal">
													<block v-if="itemName.door_name && itemName.door_name!=''">
														<block v-if="itemName.door_type==2">
															<view class="flex_one"> {{itemName.floor_name?itemName.floor_name:''}}
																{{itemName.floor_layer?itemName.floor_layer:''}} ({{itemName.door_name}})</view>
														</block>
														<block v-else>
															<view class="flex_one"> {{itemName.floor_layer?itemName.floor_layer:''}}
																{{itemName.floor_name?itemName.floor_name:''}}</view>
														</block>
													</block>
													<block v-else>
														<block v-if="itemName.door_type==2">
															<view class="flex_one"> {{itemName.door_name?itemName.door_name:''}}
																{{itemName.floor_layer?itemName.floor_layer:''}} {{itemName.floor_name?itemName.floor_name:''}}</view>
														</block>
														<block v-else>
															<view class="flex_one"> {{itemName.floor_layer?itemName.floor_layer:''}}
																{{itemName.floor_name?itemName.floor_name:''}}</view>
														</block>
													</block>

													<view> {{itemName.door_type==2?'大门':'小区单元门 '}} </view>
												</view>
												<view class="flex_one time flex">
													<view class="flex_one">{{itemName.door_user_type==1?'业主 ':itemName.door_user_type==2?'临时访客':itemName.door_user_type==3?'工作人员':'家属'}}</view>
													<block v-if="itemName.door_end_time==0">
														<view>长期有效</view>
													</block>
													<block v-else>
														<block v-if="itemName.open_status==0">
															<view>您没有权限开门，请联系物业</view>
														</block>
														<block v-else-if="itemName.open_status==2">
															<view>时间已过期，请联系物业</view>
														</block>
														<block v-else-if="itemName.open_status==3">
															<view>{{itemName.door_user_type==1?'物业欠费':itemName.door_user_type==4?'业主已欠物业费':'分享者已欠物业费'}}</view>
														</block>
														<block v-else-if="itemName.open_status==4">
															<view>已过期</view>
														</block>
														<block v-else-if="itemName.open_status==6">
															<view>获得的临时门禁权限已过期</view>
														</block>
														<block v-else-if="itemName.open_status==1">
															<view>有效期至 {{itemName.door_end_time}}</view>
														</block>
													</block>
												</view>
											</view>
										</view>
									</view>
								</block>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view :style="'height:' + (winH-30) + 'px ;overflow:hidden'" v-else>
				<view class="empty_box" style="font-size:20px">
					正在连接设备
					<view style="font-size:14px;color:#999;">正在搜寻，请尽可能将手机靠近设备</view>
				</view>
				<view style="position:relative;">
					<view class style="left:30%;text-align:center;margin-top:20px;width:100%;z-index:10;">
						<view class="flex" style="justify-content:center;">
							<image src="../../static/images/my_door.png" mode="widthFix" style="width:30%"></image>
							<image src="../../static/images/door_key.png" mode="widthFix" :style="'width:10%;margin-left:' + door_left + 'px'"></image>
						</view>
					</view>
					<view style="z-index:1;" class>
						<view style="text-align:center;margin-top:53%;position:relative">
							<image src="../../static/images/homeButton.png" mode="aspectFit" style="height:50px;width:24px"></image>
							<view>
								<view class="des" :style="'position:absolute;width:30px;left:50%;height:30px;border-radius:50%;border:1px solid #04B7A5;opacity:' + leida[0]">
									<view style="width:100%;height:100%;background:#77D8CE;opacity:0.1;border-radius:50%;"></view>
								</view>
								<view class="des" :style="'position:absolute;width:60px;left:50%;height:60px;border-radius:50%;border:1px solid #04B7A5;opacity:' + leida[1]">
									<view style="width:100%;height:100%;background:#77D8CE;opacity:0.1;border-radius:50%;"></view>
								</view>
								<view class="des" :style="'position:absolute;width:110px;left:50%;height:110px;border-radius:50%;border:1px solid #04B7A5;opacity:' + leida[2]">
									<view style="width:100%;height:100%;background:#77D8CE;opacity:0.1;border-radius:50%;"></view>
								</view>
								<view class="des" :style="'position:absolute;width:180px;left:50%;height:180px;border-radius:50%;border:1px solid #04B7A5;opacity:' + leida[3]">
									<view style="width:100%;height:100%;background:#77D8CE;opacity:0.1;border-radius:50%;"></view>
								</view>
								<view class="des" :style="'position:absolute;width:270px;left:50%;height:270px;border-radius:50%;border:1px solid #04B7A5;opacity:' + leida[4]">
									<view style="width:100%;height:100%;background:#77D8CE;opacity:0.1;border-radius:50%;"></view>
								</view>
								<view class="des" :style="'position:absolute;width:380px;left:50%;height:380px;border-radius:50%;border:1px solid #04B7A5;opacity:' + leida[5]">
									<view style="width:100%;height:100%;background:#77D8CE;opacity:0.1;border-radius:50%;"></view>
								</view>
							</view>
						</view>
					</view>

				</view>

			</view>
			<view v-if="closeDoll">
				<view class="js_dialog" id="androidDialog1" style="opacity: 1;">
					<view class="weui-mask"></view>
					<view class="weui-dialog  no_border weui-skin_android weui-dialog-active" :style="'  top:' + (is_success?'47%':'44%') + ';width:' + (is_success?'90%':'75%') + ';border-radius:5px; height:auto '">
						<view>
							<view class="rel">
								<view class="weui-dialog__bd no_border rel">
									<view :style="'max-height:' + bgheight + 'px;overflow:hidden'" class="no_border rel" @tap="goUrl" :data-url="openDoll.url"
									 :data-nums="openDoll.id" v-if="is_success">
										<image :src="openDoll.ios_pic_b" mode="widthFix" class="slide-image" style="width:100%;"></image>
									</view>
									<view style="margin-top:12%;text-align:center" v-else>
										<image src="../../static/images/home_error.png" mode="widthFix" style="width:50px;height:100%"></image>
									</view>
								</view>
								<view class="weui-dialog__ft border_rs no_border rel" :style="'background:#fff;color:#000;padding:' + (is_success?'5% 2% 5% 2%;':'10%')">
									<block v-if="is_success">
										<view class="weui-dialog__btn weui-dialog__btn_primary flex no_border" style="font-size:18px;justify-content:center">
											<image src="../../static/images/open_success.png" style="width:20px;height:20px;border-radius:50%;margin-right:2px"></image>
											<view>开门成功!</view>
										</view>
										<view class="weui-dialog__btn weui-dialog__btn_primary no_border" style="font-size:12px;color:#999">{{openDoll.open_lottery_txt}}</view>
									</block>
									<block v-else>
										<view class="weui-dialog__btn weui-dialog__btn_primary flex no_border" style="font-size:18px;justify-content:center">
											<view>{{openError==''?'开门失败!':'搜索门禁失败'}}</view>
										</view>

										<view class="weui-dialog__btn weui-dialog__btn_primary no_border" style="font-size:12px;color:#999">{{openError==''?'请重新尝试':openError}}</view>

										<view style="padding-top:13px;">
											<button size="default" type="primary" @tap="hideModel" style="display:inline-block;color:#fff;background:#04B7A5;font-size:12px;border-radius:100px;padding:0px 18px">知道了</button>
										</view>
									</block>
								</view>
								<view style="position:absolute;bottom:-77px;left:47%;" v-if="is_success">
									<image src="../../static/images/door_pic_del.png" @tap="hideModel" style="width:30px;height:30px;border-radius:50%;"></image>
								</view>
							</view>
						</view>

					</view>
				</view>
			</view>
		</view>
		<view class="homeBg" v-if="!open_leidr">
			<!--
			<view style="height:40px;width:40px;position:absolute;bottom:55px;right:40px;z-index:10;text-align:center" @tap="set_top_msg"
			 v-if="set_opacity">
				<image src="../../static/images/door_set.png " mode="widthFix " style="height:20px;width:20px;padding-top:10px"></image>
			</view>
			-->
			<view class="flex" style="padding-left:10px;" v-if="system">
				<image src="../../static/images/homeExplain.png" style="width:12px;height:12px"></image>
				<view class="flex_one" style="color:#999;font-size:12px;padding-left:5px">开门前您可能需要开启定位才能正常使用</view>
			</view>
			<view class="open_door" :style="'height:' + img_w + 'px'" @tap="door">
				<button size="default" type="primary" class="confire open_door_button">一键开门</button>
				<image src="../../static/images/open_door.png" style="width:100%;height:100%"></image>
			</view>
		</view>
	</view>
</template>

<script>
	var app = getApp();
	var common = require('../../utils/common.js');
	var myaudio;
	var time_index = 0;
	var createBLEConnectionNumber = 0;
	var error_tip = '抱歉！暂未搜索到门禁设备，请靠近门禁后重新尝试';
	var phoneInfo = wx.getSystemInfoSync();
	var _this;
	// 初始化蓝牙适配器
	const initBluetooth = () => {
		wx.openBluetoothAdapter({
			success(res) {
				console.log("初始化蓝牙模块 --- 已开启");
				_this.blueAdapter = true;
				searchBluetooth();
			},

			fail(res) {
				console.log("初始化蓝牙模块 --- 未开启", res);
				var errMsg = res.errMsg.replace("openBluetoothAdapter:fail", "");
				errMsg = errMsg.replace(/(^\s*)|(\s*$)/g, "");

				if (res.errCode == 10001 || errMsg.indexOf("errCode = 10001") != -1 || errMsg.indexOf("errCode=10001") != -1 ||
					errMsg.indexOf("available") != -1) {
					errMsg = "您的手机未开启蓝牙或者当前蓝牙适配器不可用，请重新打开蓝牙后再点击开门";
				}

				wx.showModal({
					title: '提示：',
					content: errMsg,
					showCancel: false
				});
			}

		});
	}; // 查找设备
	// 查找设备
	const searchBluetooth = () => {
		animate('open');
		wx.startBluetoothDevicesDiscovery({
			allowDuplicatesKey: false,
			success: res => {
				console.log("查找设备");
				watchBluetoothFound(); // 11s 停止搜索

				_this.discoveryTimer = setTimeout(stopSearchBluetooth, 11000);
			},
			fail: res => {
				common.log_report({
					errorRes: res,
					userLocation: wx.getStorageSync('userLocation')
				}, 'wxapp_startDiscoveryFail_error_log');
				console.log('开启蓝牙搜索失败startBluetoothDevicesDiscovery:fail', res);
			}
		});
	}; // 监听寻找到新设备
	// 监听寻找到新设备
	const watchBluetoothFound = () => {
		wx.onBluetoothDeviceFound(res => {
			console.log('555555555555', res, _this.doorList);
			var device = res.devices[0];

			_this.devicesArr.push(device.name);

			_this.devicesObjArr.push(device);

			if (device.name.substr(0, 2) == '05' || device.name.substr(0, 2) == '0C' || device.name.length == '17' && device.name
				.substr(-5) == 'BLOCK') {
				if (_this.doorList[device.name.substr(2, 8)]) {
					_this.deviceName = device.name.substr(2, 8);
				} else if (_this.doorList[device.name]) {
					_this.deviceName = device.name;
				}

				console.log('3333333333333333', device.name, _this.doorList, _this.deviceName);

				if (_this.deviceName && _this.deviceId == '') {
					_this.deviceId = device.deviceId;
					_this.lockData = _this.doorList[_this.deviceName][1];
					_this.doorId = _this.doorList[_this.deviceName][0];
					console.info('连接成功---', _this.deviceId);
					connectBluetooth(); // 连接成功 需要断开蓝牙搜索

					stopSearchBluetooth('success');
				}
			}
		});
	}; // 停止蓝牙搜索
	// 停止蓝牙搜索
	const stopSearchBluetooth = status => {
		wx.stopBluetoothDevicesDiscovery({
			success: function(res) {
				console.log("停止查找", _this.deviceId, status, _this.deviceName);

				if (!status) {
					animate('close');
					var res = '扫描门禁失败';
					closeConnectBluetooth(res, 'wxapp_notfounddoor_error_log');
				} else {
					clearTimeout(_this.discoveryTimer);
				}
			}
		});
	}; // 连接设备
	// 连接设备
	const connectBluetooth = () => {
		console.info('connectBluetooth', _this.deviceId);
		wx.createBLEConnection({
			deviceId: _this.deviceId,

			success(res) {
				console.log("连接成功设备---" + JSON.stringify(res));
				getBluetoothServers();
			},

			fail(err) {
				closeConnectBluetooth(err, 'wxapp_createBLEConnection_error_log');
				console.log("连接失败，结束---");
			}

		});
	}; // 断开连接
	// 断开连接
	const closeConnectBluetooth = (res, name, success) => {
		common.log_report({
			door_id: _this.doorId,
			devicesArr: _this.devicesArr,
			devicesObjArr: _this.devicesObjArr,
			errorRes: res,
			userLocation: wx.getStorageSync('userLocation')
		}, name);

		if (res == '扫描门禁失败') {
			_this.closeDoll = true;
			_this.is_success = false;
			_this.openError = error_tip;

			console.log('344444444444444444444444未找到蓝牙设备');
			closeBluetoothAdapter();
		} else {
			// 断开BLE的连接
			wx.closeBLEConnection({
				deviceId: _this.deviceId,

				success(res) {
					console.log("手动断开连接");
					console.log('未开始重连', _this.reconnect_num, success);

					if (_this.reconnect_num < 2 && !success && _this.deviceId) {
						console.log('开始重连', _this.reconnect_num);
						_this.reconnect_num++;
						connectBluetooth();
						return;
					} // 没有连接成功的弹窗提示


					if (!success) {
						animate('close');
						common.post('House&a=village_door_info', {
							door_device_id: _this.deviceName
						}, function(fail) {
							_this.closeDoll = true;
							_this.is_success = false;
							_this.openError = fail.tip == 1 ? error_tip : fail.tip_msg;
						});
					}

					closeBluetoothAdapter();
				},

				fail() {
					closeConnectBluetooth();
				}

			});
		}
	};
	const closeBluetoothAdapter = () => {
		// 断开蓝牙的连接 （初始化所有的状态）
		wx.closeBluetoothAdapter({
			success(res) {
				console.log('断开蓝牙适配器', res);
				_this.devicesArr = [];
				_this.devicesObjArr = [];
				_this.doorId = '';
				_this.deviceId = '';
				_this.reconnect_num = 0;
				_this.open_door_success = false;
				_this.blueAdapter = false;
			}

		});
	}; // 获取设备服务
	// 获取设备服务
	const getBluetoothServers = () => {
		wx.getBLEDeviceServices({
			deviceId: _this.deviceId,

			success(res) {
				console.log('获取设备服务', res.services);

				for (var i = 0; i < res.services.length; i++) {
					if (res.services[i].uuid.indexOf("fee7") != -1 || res.services[i].uuid.indexOf("FEE7") != -1) {
						console.log('设备服务ID', res.services[i].uuid);
						_this.serviceId = res.services[i].uuid;
						break;
					}
				}

				getBluetoothCharacteristics();
			},

			fail(res) {
				closeConnectBluetooth(res, 'wxapp_getBLEDeviceServices_error_log');
			}

		});
	}; // 获取设备某个服务特征值列表
	// 获取设备某个服务特征值列表
	const getBluetoothCharacteristics = () => {
		wx.getBLEDeviceCharacteristics({
			deviceId: _this.deviceId,
			serviceId: _this.serviceId,

			success(res) {
				console.info('获取设备某个服务特征值列表', res);

				for (var i = 0; i < res.characteristics.length; i++) {
					if (res.characteristics[i].uuid.indexOf("fec6") != -1 || res.characteristics[i].uuid.indexOf("FEC6") != -1) {
						_this.characteristicId = res.characteristics[i].uuid;
						break;
					}
				}

				if (res.characteristics[0].properties && res.characteristics[0].properties.write) {
					var typedArray = new Uint8Array(_this.lockData.match(/[\da-f]{2}/gi).map(function(h) {
						return parseInt(h, 16);
					}));
					_this.writeValue = typedArray.buffer;
					console.log('writeValue', _this.writeValue);
					notifyBluetoothCharacteristicValueChange();
				} else {
					console.log('蓝牙设备无法写数据', res.characteristics);
					closeConnectBluetooth(res, 'wxapp_unableToWriteCharacteristics_error_log');
				}
			},

			fail(res) {
				closeConnectBluetooth(res, 'wxapp_getBLEDeviceCharacteristics_error_log');
			}

		});
	}; // 启用设备特征值变化时的 notify 功能
	// 启用设备特征值变化时的 notify 功能
	const notifyBluetoothCharacteristicValueChange = () => {
		wx.notifyBLECharacteristicValueChange({
			deviceId: _this.deviceId,
			serviceId: _this.serviceId,
			characteristicId: _this.characteristicId,
			state: true,

			success(notifyRes) {
				console.log("启用设备特征值变化时的 notify 功能", notifyRes);
				watchBluetoothCharacteristicValueChange();
			},

			fail(res) {
				closeConnectBluetooth(res, 'wxapp_notifyBLECharacteristicValueChange_error_log');
			}

		});
	}; // 监听设备的特征值变化
	// 监听设备的特征值变化
	const watchBluetoothCharacteristicValueChange = () => {
		wx.onBLECharacteristicValueChange(function(res) {
			console.log('监听设备的特征值变化', res);
			console.log('返回数据', common.ab2hext(res.value));
			var changeValue = common.ab2hext(res.value);
			closeConnectBluetooth(res, 'wxapp_openSuccess_log', true);
		});
		setTimeout(() => {
			writeBluetoothCharacteristicValue();
		}, 50);
	}; // 向设备特征值中写入二进制数据
	// 向设备特征值中写入二进制数据
	const writeBluetoothCharacteristicValue = () => {
		wx.writeBLECharacteristicValue({
			deviceId: _this.deviceId,
			serviceId: _this.serviceId,
			characteristicId: _this.characteristicId,
			value: _this.writeValue,

			success(res) {
				console.log("写入成功");
				openDoorSuccess();
			},

			fail(res) {
				console.log("写入失败 结束");
				closeConnectBluetooth(res, 'wxapp_writeBLECharacteristicValue_error_log');
			}

		});
	};
	// 开门成功请求
	const openDoorSuccess = () => {
		_this.open_door_success = true;
		common.post('Login&a=open_door_notice', {
			door_id: _this.doorId
		}, data => {
			animate('close');

			if (data) {
				if (data.voice_mp3) {
					doorVideo(data.voice_mp3);
				}

				if (data.url) {
					_this.openDoll = data;
					_this.closeDoll = true;
					_this.is_success = true;
					_this.auto_page_close_adver = setTimeout(function() {
						_this.goback();
					}, 5000);
				}else{
					wx.showToast({
						title: '开门成功',
						icon: 'success',
						duration: 5000,
						success: function() {
							_this.auto_page_close_adver = setTimeout(function() {
								_this.goback();
							}, 5000);
						}
					});
				}
			} else {
				wx.showToast({
					title: '开门成功',
					icon: 'success',
					duration: 5000,
					success: function() {
						_this.auto_page_close_adver = setTimeout(function() {
							_this.goback();
						}, 5000);
					}
				});
			}
		}, () => {
			animate('close');
			
			wx.showToast({
				title: '开门成功',
				icon: 'success',
				duration: 5000,
				success: function() {
					_this.auto_page_close_adver = setTimeout(function() {
						_this.goback();
					}, 5000);
				}
			});
		});
	}; // 获取门禁信息列表
	// 获取门禁信息列表
	const get_open_door_list = data => {
		console.log('user_visitor_open_list', data);

		if (data.door_info) {
			_this.doorList = data.door_info;
		}

		var is_one = 0;

		for (var i in data.open_list_info) {
			is_one++;
			data.open_list_info[i].is_all = true;

			if (data.open_list_info[i].door_list && !_this.open_status) {
				for (var n in data.open_list_info[i].door_list) {
					// 是否有门可以打开
					if (data.open_list_info[i].door_list[n].open_status == 1) {
						_this.open_status = true;
						break;
					}
				}
			}
		} // 自动开门


		if (data.auto_page_door) {
			_this.door();
		}

		_this.bgheight = phoneInfo.windowWidth * 0.9 * 353 / 506;
		_this.img_w = phoneInfo.windowWidth * 0.3;
		_this.error_door = phoneInfo.windowWidth * 0.6 + 'px';
		_this.village_door = data.open_list_info;
		_this.is_one = is_one;
		_this.winH = phoneInfo.windowHeight;
		_this.set_opacity = data.auto_open_door === true ? true : false;
		_this.auto_page_door = data.auto_page_door;

		console.log('_this.village_door', _this.village_door);

		console.log('set_opacity', _this.set_opacity);
		wx.hideLoading();
	};

	// 播放开门成功音效
	const doorVideo = res => {
		console.log(res);
		console.log('播放');
		myaudio.src = res;
		myaudio.autoplay = true;
		myaudio.volume = 1;
		myaudio.obeyMuteSwitch = false;
		myaudio.play();
		myaudio.onPlay(() => {
			console.log('开始播放');
		});
		myaudio.onError(res => {
			console.log(res.errMsg);
			console.log('播放错误');
		});
	};

	// 开门按钮动画
	const animate = status => {
		if (status == 'open') {
			_this.open_leidr = true;
			_this.leida = [1, 1, 0.1, 0.1, 0.1, 0.1];
		} else {
			clearInterval(_this.time2);
			clearInterval(_this.time1);

			_this.open_leidr = false;

			_this.blueAdapter = false;
			return;
		}

		time_index = 0;
		var n = 1;
		var list = [
			[1, 0.1, 0.1, 0.1, 0.1, 0.1],
			[1, 1, 0.1, 0.1, 0.1, 0.1],
			[1, 1, 1, 0.1, 0.1, 0.1],
			[1, 1, 1, 1, 0.1, 0.1],
			[1, 1, 1, 1, 1, 0.1],
			[1, 1, 1, 1, 1, 1]
		];
		_this.time1 = setInterval(function() {
			n++;
			time_index++;

			if (n == 6) {
				n = 0;
			}

			_this.leida = list[n];
		}, 500);
		_this.time2 = setInterval(function() {
			var l = _this.door_left - 1;

			if (l == -26) {
				l = -11;
			}

			_this.door_left = l;
		}, 100);
	};

	export default {
		data() {
			return {
				openDoll: {},
				closeDoll: false,
				bgheight: 0,
				is_login: false,
				leida: [1, 1, 0.1, 0.1, 0.1, 0.1],
				door_left: -11,
				open_leidr: false,
				is_success: false,
				time1: null,
				time2: null,
				img_w: 112,
				error_door: 0,
				open_status: false,
				is_set_top: true,
				is_one: 1,
				winH: 675,
				video_src: '',
				set_opacity: false,
				openError: '',
				system: false,
				auto_page_door: false,
				auto_page_door_type: false,
				auto_page_close_adver: null,
				doorList: [],
				devicesArr: [],
				// 搜索到的设备名称数组
				devicesObjArr: [],
				// 搜索到的设备数组
				doorId: '',
				// 能被打开的门禁ID
				deviceId: '',
				// 蓝牙设备ID
				reconnect_num: 0,
				// 重新连接的次数，每次最多重连3次
				open_door_success: false,
				// 是否开门成功
				blueAdapter: false,
				//是否开启了蓝牙适配器
				discoveryTimer: '',
				village_door: {}
			};
		},

		onUnload: function() {
			// 页面关闭
			if (_this.auto_page_close_adver != null) {
				clearTimeout(_this.auto_page_close_adver);
			}

			animate('close');
		},
		onHide: function() {
			// 页面隐藏
			animate('close');
		},
		onShow: function() {},
		onLoad: function(opt) {
			_this = this;
			wx.showLoading({
				title: "加载中"
			});
			console.log(phoneInfo);

			_this.system = phoneInfo.system.indexOf('Android') == -1 ? false : true;

			app.globalData.door_share_id = '';
			myaudio = wx.createInnerAudioContext();
			common.setMainColor(_this, function(config) {
				var user_visitor_open_list = wx.getStorageSync('user_visitor_open_list');
				console.log('333333333333', user_visitor_open_list);

				if (user_visitor_open_list && user_visitor_open_list.aDoor && user_visitor_open_list.aDoor.length > 0) {
					get_open_door_list(user_visitor_open_list);
				} else {
					common.post('House&a=user_visitor_open_list', {
						noTip: true
					}, function(data) {
						get_open_door_list(data);
					});
				}
			});
		},
		components: {},
		props: {},
		methods: {
			set_top_msg: function() {
				wx.navigateTo({
					url: "/pages/share/set"
				});
			},
			goUrl: function(e) {
				_this.leida = [1, 1, 0.1, 0.1, 0.1, 0.1];

				var nums = e.currentTarget.dataset.nums;
				var pageTitle = e.currentTarget.dataset.url_title;
				var url = e.currentTarget.dataset.url;

				if (!pageTitle) {
					pageTitle = '';
				}

				if (nums) {
					common.post('Login&a=house_adver_click', {
						adver_id: nums
					}, function(e) {
						common.parseUrl(url, '', false, pageTitle);
					});
				} else {
					common.parseUrl(url, '', false, pageTitle);
				}
			},
			door: function() {
				if (Object.keys(_this.doorList).length == 0) {
					wx.showModal({
						title: '提示：',
						content: '暂无可开门的门禁',
						showCancel: false
					});
					return;
				}

				if (!_this.open_status) {
					wx.showModal({
						title: '提示：',
						content: '门禁已失效',
						showCancel: false
					});
					return;
				}

				if (_this.open_leidr) {
					wx.showToast({
						title: '请重新点击开门',
						icon: 'none'
					});
					return;
				}

				if (_this.blueAdapter) {
					wx.closeBluetoothAdapter({
						success(res) {
							console.log('断开蓝牙', res);
							_this.devicesArr = [];
							_this.devicesObjArr = [];
							_this.doorId = '';
							_this.deviceId = '';
							_this.reconnect_num = 0;
							_this.open_door_success = false;
							_this.blueAdapter = false;

							_this.door();
						}

					});
					return;
				} // 初始化蓝牙设备


				initBluetooth();
			},
			hideModel: function() {
				error_tip = '抱歉！暂未搜索到门禁设备，请靠近门禁后重新尝试';
				animate('close');

				_this.closeDoll = false;
				_this.is_success = false;
				_this.openError = '';

				if (_this.auto_page_door && _this.open_door_success) {
					_this.goback();
				}
			},
			is_all: function(e) {
				console.log(e);
				var index = e.target.dataset.index;
				var d_list = _this.village_door;
				d_list[index].is_all = !d_list[index].is_all;

				_this.village_door = d_list;
			},
			goback: function() {
				var pages = getCurrentPages();

				if (pages.length > 0 && pages[pages.length - 1].route == 'pages/share/share' && _this.auto_page_door) {
					wx.navigateBack({
						delta: 1
					});
				}
			},

			success(res) {
				console.log("初始化蓝牙模块 --- 已开启");
				_this.blueAdapter = true;
				searchBluetooth();
			},

			fail(res) {
				console.log("初始化蓝牙模块 --- 未开启", res);
				var errMsg = res.errMsg.replace("openBluetoothAdapter:fail", "");
				errMsg = errMsg.replace(/(^\s*)|(\s*$)/g, "");

				if (res.errCode == 10001 || errMsg.indexOf("errCode = 10001") != -1 || errMsg.indexOf("errCode=10001") != -1 ||
					errMsg.indexOf("available") != -1) {
					errMsg = "您的手机未开启蓝牙或者当前蓝牙适配器不可用，请重新打开蓝牙后再点击开门";
				}

				wx.showModal({
					title: '提示：',
					content: errMsg,
					showCancel: false
				});
			},

			success: res => {
				console.log("查找设备");
				watchBluetoothFound(); // 11s 停止搜索

				_this.discoveryTimer = setTimeout(stopSearchBluetooth, 11000);
			},
			fail: res => {
				common.log_report({
					errorRes: res,
					userLocation: wx.getStorageSync('userLocation')
				}, 'wxapp_startDiscoveryFail_error_log');
				console.log('开启蓝牙搜索失败startBluetoothDevicesDiscovery:fail', res);
			},
			success: function(res) {
				console.log("停止查找", _this.deviceId, status, _this.deviceName);

				if (!status) {
					animate('close');
					var res = '扫描门禁失败';
					closeConnectBluetooth(res, 'wxapp_notfounddoor_error_log');
				} else {
					clearTimeout(_this.discoveryTimer);
				}
			},

			success(res) {
				console.log("连接成功设备---" + JSON.stringify(res));
				getBluetoothServers();
			},

			fail(err) {
				closeConnectBluetooth(err, 'wxapp_createBLEConnection_error_log');
				console.log("连接失败，结束---");
			},

			success(res) {
				console.log("手动断开连接");
				console.log('未开始重连', _this.reconnect_num, success);

				if (_this.reconnect_num < 2 && !success && _this.deviceId) {
					console.log('开始重连', _this.reconnect_num);
					_this.reconnect_num++;
					connectBluetooth();
					return;
				} // 没有连接成功的弹窗提示


				if (!success) {
					animate('close');
					common.post('House&a=village_door_info', {
						door_device_id: _this.deviceName
					}, function(fail) {
						_this.closeDoll = true;
						_this.is_success = false;
						_this.openError = fail.tip == 1 ? error_tip : fail.tip_msg;
					});
				}

				closeBluetoothAdapter();
			},

			fail() {
				closeConnectBluetooth();
			},

			success(res) {
				console.log('断开蓝牙适配器', res);
				_this.devicesArr = [];
				_this.devicesObjArr = [];
				_this.doorId = '';
				_this.deviceId = '';
				_this.reconnect_num = 0;
				_this.open_door_success = false;
				_this.blueAdapter = false;
			},

			success(res) {
				console.log('获取设备服务', res.services);

				for (var i = 0; i < res.services.length; i++) {
					if (res.services[i].uuid.indexOf("fee7") != -1 || res.services[i].uuid.indexOf("FEE7") != -1) {
						console.log('设备服务ID', res.services[i].uuid);
						_this.serviceId = res.services[i].uuid;
						break;
					}
				}

				getBluetoothCharacteristics();
			},

			fail(res) {
				closeConnectBluetooth(res, 'wxapp_getBLEDeviceServices_error_log');
			},

			success(res) {
				console.info('获取设备某个服务特征值列表', res);

				for (var i = 0; i < res.characteristics.length; i++) {
					if (res.characteristics[i].uuid.indexOf("fec6") != -1 || res.characteristics[i].uuid.indexOf("FEC6") != -1) {
						_this.characteristicId = res.characteristics[i].uuid;
						break;
					}
				}

				if (res.characteristics[0].properties && res.characteristics[0].properties.write) {
					var typedArray = new Uint8Array(_this.lockData.match(/[\da-f]{2}/gi).map(function(h) {
						return parseInt(h, 16);
					}));
					_this.writeValue = typedArray.buffer;
					console.log('writeValue', _this.writeValue);
					notifyBluetoothCharacteristicValueChange();
				} else {
					console.log('蓝牙设备无法写数据', res.characteristics);
					closeConnectBluetooth(res, 'wxapp_unableToWriteCharacteristics_error_log');
				}
			},

			fail(res) {
				closeConnectBluetooth(res, 'wxapp_getBLEDeviceCharacteristics_error_log');
			},

			success(notifyRes) {
				console.log("启用设备特征值变化时的 notify 功能", notifyRes);
				watchBluetoothCharacteristicValueChange();
			},

			fail(res) {
				closeConnectBluetooth(res, 'wxapp_notifyBLECharacteristicValueChange_error_log');
			},

			success(res) {
				console.log("写入成功");
				openDoorSuccess();
			},

			fail(res) {
				console.log("写入失败 结束");
				closeConnectBluetooth(res, 'wxapp_writeBLECharacteristicValue_error_log');
			},

			success: function() {
				_this.auto_page_close_adver = setTimeout(function() {
					_this.goback();
				}, 5000);
			},
			success: function() {
				_this.auto_page_close_adver = setTimeout(function() {
					_this.goback();
				}, 5000);
			}
		}
	};
</script>
<style>
	/* pages/webview/webview.css */
	.empty_box {
		padding: 35px 35px 0px 35px;
		font-size: 15px;
		text-align: center
	}

	page {
		background: #fff
	}

	.confire {
		background-color: #06c1ae !important;
		margin: 0px
	}

	.buttons {
		margin: auto;
	}

	.container {
		padding: 15px;
	}

	.home {
		background: #fff;
		border-radius: 10px;
		margin: 10px 5px 5px 5px;
		box-shadow: #E7F8F0 0px 0px 10px
	}

	.rel {
		position: relative
	}

	.no_border:before,
	.no_border:after {
		content: none !important;
	}

	.border_rs {
		border-bottom-left-radius: 5px;
		border-bottom-right-radius: 5px
	}

	.weui-media-box_appmsg {
		display: -webkit-box;
		display: -webkit-flex;
		display: flex;
		-webkit-box-align: center;
		-webkit-align-items: center;
		align-items: center;
		padding: 10px 10px;
		position: relative;
	}

	.weui-media-box_appmsg .weui-media-box__hd {
		margin-right: .8em;
		width: 20px;
		text-align: center;
	}

	.weui-media-box_appmsg .weui-media-box__bd {
		-webkit-box-flex: 1;
		-webkit-flex: 1;
		flex: 1;
		min-width: 0;
	}

	.weui-media-box__title .h4 {
		font-size: 16px;
	}

	.weui-media-box__title .time {
		color: #999;
		font-size: 12px
	}

	.weui-media-box__desc.all {
		color: #04B7A5
	}

	.flex {
		display: flex !important;
		display: -webkit-box;
		display: -moz-box;
		display: -ms-flexbox;
		display: -webkit-flex;
		align-items: center;
	}

	.flex_one {
		flex: 1;
		-webkit-box-flex: 1;
		-webkit-flex: 1;
	}

	.border-t:before {
		border-top: 1px solid #e9e9e9;
		content: '';
		display: block;
		width: 100%;
		position: absolute;
		left: 0;
		top: 0;
		-webkit-transform-origin: left top;
		-webkit-transform: scaleY(0.5);
	}

	.home_detail {
		background: #E5F8F6;
		border-bottom-left-radius: 10px;
		border-bottom-right-radius: 10px;
	}

	.home_detail .weui-media-box_appmsg.border-t:first-child::before {
		border: none;
	}

	.homeBg {
		position: fixed;
		bottom: 0px;
		width: 100%;
		height: 150px;
		z-index: 100
	}

	.open_door {
		width: 30%;
		max-width: 118px;
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		transform-origin: 0 0;
		-webkit-transition-duration: .2s;
		transition-duration: .2s;
		-webkit-transform: translate(-50%, -50%);
		-webkit-transform-origin: 0 0;
	}

	.leida {
		top: 0%;
		left: 50%;
		transform: translate(-50%, -50%);
		transform-origin: 0 0;
		-webkit-transition-duration: .2s;
		transition-duration: .2s;
		-webkit-transform: translate(-50%, -50%);
		-webkit-transform-origin: 0 0;
		margin-top: 100%;
	}

	.des {
		-webkit-transition-duration: .2s;
		overflow: hidden;
		transition-duration: .2s;
		-webkit-transform: translate(-50%, -50%);
		transform: translate(-50%, -50%);
		-webkit-transform-origin: 0 0;
		transform-origin: 0 0;
		margin: 0;
		top: 45%;
	}

	.open_door_button {
		position: absolute;
		width: 80%;
		height: 80%;
		z-index: 10;
		opacity: 0;
		border-radius: 50%;
		left: 10%;
		top: 10%;
	}
</style>
